﻿using AutoMapper;
using Common.Enum;
using Entity.ERP.DTO.PurchaseArriveOrder;
using Entity.ERP.Entity;
using Entity.ERP.View.PurchaseArriveOrder;
using Entity.ERP.View.PurchaseArriveOrderItem;
using Entity.WMS.Entity;
using FrameWork.DataContext;
using FrameWork.DataHelper;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;
using static Common.Enum.StateEnum;

namespace Service.ERP
{
    public class PurchaseArriveOrderService
    {
        /**
         * 数据库上下文
         */
        private readonly DataContext _context;

        /**
         * 自动映射器
         */
        private readonly IMapper _mapper;

        /**
         * 构造注入
         */
        public PurchaseArriveOrderService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取采购到货单列表
         */
        public async Task<RequestResponseModel<PageResult<PurchaseArriveOrderView>>> GetPurchaseArriveList(PurchaseArriveOrderSearchDTO purchaseArriveOrderSearchDTO)
        {
            // 筛选
            var query = _context.PurchaseArriveOrderView
                .WhereIF(a => a.Code.Contains(purchaseArriveOrderSearchDTO.Code), !string.IsNullOrEmpty(purchaseArriveOrderSearchDTO.Code))
                .WhereIF(a => a.SupplierName.Contains(purchaseArriveOrderSearchDTO.SupplierName), !string.IsNullOrEmpty(purchaseArriveOrderSearchDTO.SupplierName))
                .WhereIF(a => a.Status == purchaseArriveOrderSearchDTO.Status, purchaseArriveOrderSearchDTO.Status != null)
                .WhereIF(a => a.ExamStatus == purchaseArriveOrderSearchDTO.ExamStatus, purchaseArriveOrderSearchDTO.ExamStatus != null);

            // 返回列表
            var purchaseArriveOrderList = await query
                .Page(purchaseArriveOrderSearchDTO.CurrentPage, purchaseArriveOrderSearchDTO.PageSize)
                .ToListAsync();

            // 计算总数
            var pageCount = await query.CountAsync();

            // 返回数据
            var pageResult = new PageResult<PurchaseArriveOrderView>(purchaseArriveOrderList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 采购到货单子单列表
         */
        public async Task<RequestResponseModel<PageResult<PurchaseArriveOrderItemView>>> GetPurchaseArriveOrderItemList(PurchaseArriveOrderItemSearchDTO purchaseArriveOrderItemSearchDTO)
        {
            // 筛选
            var query = _context.PurchaseArriveOrderItemView
                .Where(a => a.PurchaseArriveOrderId == purchaseArriveOrderItemSearchDTO.Id);

            // 返回列表
            var purchaseArriveOrderItemList = await query
                .Page(purchaseArriveOrderItemSearchDTO.CurrentPage, purchaseArriveOrderItemSearchDTO.PageSize)
                .ToListAsync();

            // 计算总数
            var pageCount = await query.CountAsync();

            // 返回数据
            var pageResult = new PageResult<PurchaseArriveOrderItemView>(purchaseArriveOrderItemList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 新增采购到货单
         */
        public async Task<RequestResponseModel<string>> AddPurchaseArriveOrder(PurchaseArriveOrderAddDTO purchaseArriveOrderAddDTO)
        {
            // 处理主单单据
            var purchaseArriveOrder = _mapper.Map<PurchaseArriveOrderModel>(purchaseArriveOrderAddDTO);
            purchaseArriveOrder.Id = Guid.NewGuid().ToString();
            purchaseArriveOrder.Status = StateEnum.PurchaseType.待生成;  // 采购类型状态
            purchaseArriveOrder.ExamStatus = StateEnum.ExamStatus.待审核;
            purchaseArriveOrder.CreateTime = DateTime.Now;

            // 处理子单数据
            var purchaseArriveOrderItemList = _mapper.Map<List<PurchaseArriveOrderItemModel>>(purchaseArriveOrderAddDTO.Items);
            foreach (var item in purchaseArriveOrderItemList)
            {
                item.Id = Guid.NewGuid().ToString();
                item.PurchaseArriveOrderId = purchaseArriveOrder.Id;
            }

            // 修改并保存数据库
            _context.PurchaseArriveOrder.Add(purchaseArriveOrder);
            _context.PurchaseArriveOrderItem.AddRange(purchaseArriveOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "新增成功", purchaseArriveOrder.Id);
        }

        /**
         * 删除采购到货单
         */
        public async Task<RequestResponseModel<string>> DeletePurchaseArriveOrder(string Id)
        {
            // 校验id有效性
            var query = await Valid.ValidId(_context.PurchaseArriveOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "id无效", Id);
            }

            // 已审核的单据无法删除
            if (query.Status != StateEnum.PurchaseType.待生成)
            {
                return RequestResponse.CreateResponse(400, "只有待生成的单据才能删除", Id);
            }

            // 查找该id下的子单
            var purchaseDeliveryOrderItemList = _context.PurchaseArriveOrderItem
                .Where(a => a.PurchaseArriveOrderId == Id);

            // 操作数据库并保存
            _context.PurchaseArriveOrder.Remove(query);
            _context.PurchaseArriveOrderItem.RemoveRange(purchaseDeliveryOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "删除成功", Id);
        }

        /**
         * 审核通过采购到货单
         */
        public async Task<RequestResponseModel<string>> PassPurchaseArriveOrder(string Id)
        {
            // 校验id
            var query = await Valid.ValidId(_context.PurchaseArriveOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            // 校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核通过", Id);
            }

            // 修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核通过;

            // 修改并保存数据库
            _context.PurchaseArriveOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核通过成功", Id);
        }

        /**
         * 审核不通过采购到货单
         */
        public async Task<RequestResponseModel<string>> UnPassPurchaseArriveOrder(string Id)
        {
            // 校验id
            var query = await Valid.ValidId(_context.PurchaseArriveOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            // 校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核不通过", Id);
            }

            // 修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核不通过;

            // 修改并保存数据库
            _context.PurchaseArriveOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核不通过成功", Id);
        }

        /**
         * 反审核采购到货单
         */
        public async Task<RequestResponseModel<string>> CancelPassPurchaseArriveOrder(string Id)
        {
            // 校验id
            var query = await Valid.ValidId(_context.PurchaseArriveOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            // 校验状态
            if (query.Status != StateEnum.PurchaseType.待入库)
            {
                return RequestResponse.CreateResponse(400, "只有待推送的单据才可以反审核", Id);
            }

            // 修改数据
            query.ExamStatus = StateEnum.ExamStatus.待审核;

            // 修改并保存数据库
            _context.PurchaseArriveOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "反审核成功", Id);
        }


        /**
         * 推送
         */
        public async Task<RequestResponseModel<string>> PushPurchaseArriveOrder(string Id)
        {
            // 校验id
            var query = await Valid.ValidId(_context.PurchaseArriveOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            // 校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.审核通过)
            {
                return RequestResponse.CreateResponse(400, "只有审核通过的单据才可以推送", Id);
            }

            // 修改数据
            query.Status = PurchaseType.待入库;
            var items = await _context.PurchaseArriveOrderItem.Where(a => a.PurchaseArriveOrderId == query.Id).ToListAsync();
            //创建仓库出库单
            foreach (var item in items)
            {
                var order = new WarehousePurchaseModel()
                {
                    Id = Guid.NewGuid().ToString(),
                    PurchaseArriveOrderItemId = item.Id,
                    CardNo = query.CardNo,
                    GoodsId = item.GoodsId,
                    NumberArrive = item.NumberArrive
                };
                _context.Add(order);
            }
            // 修改并保存数据库
            _context.PurchaseArriveOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "推送成功", Id);
        }

    }
}
